#!/bin/bash
sites="manhua.178|178.com/mh|imagefap.com/profile|imagefap.com/gallery|imagefap.com/pictures|imagefap.com/showfav|imagebam.com/gallery|imagebam.com/image"
get_site() {
  echo "$1" | grep -Eo "$sites"
}

178.com/mh() {
  manhua.178 "$1"
}

manhua.178() {
  PAGE=`curl -s -A iPad --compressed "$1"`
  logf=`echo "$PAGE" | grep -m 1 "^var pages"`
  if [ -z "$logf" ]; then
    logf=`echo "$PAGE" | sed -n '/cartoon_online_border/,/clearfix/p' | grep -o 'http[^"]*html'`
    echo "$logf"
    [ -z "$logf" ] && exit;
    while read alburl; do
      manhua.178 "$alburl"
    done <<< "$logf"
    return 0
  fi
  logf=${logf// /%20}
  flist=`echo "$logf" | grep -o '"[^"]*"' |cut -d'/' -f 4|tr -d '"'`
  flist=`echo $flist | tr ' ' ','`
  flist=`zsh -c "echo -e '$flist' | tr -d '\'"`
  furl=`echo "$logf" | grep -m 1 '"[^"]*' | cut -d'"' -f2`
  furl=`zsh -c "echo -e '$furl' | tr -d '\'"`
  furl=${furl%/*}
  echo $furl
  # echo $flist
  curl -# -A iPad -L --create-dirs "http://manhua.178.com/imgs/${furl}/{$flist}" -o "${furl:2}/#1"
}
imagefap.com/pictures() {
  imagefap.com/gallery "${1%/*}"
}
imagefap.com/gallery() {
  gid=${1##*/}
  gid=${gid##*=}
  imgs=`curl -s "http://www.imagefap.com/pictures/$gid/?view=2" | grep -o 'fap.to[^"]*'`
  cnt=1
  echo = $gid =
  for img in $imgs; do
    echo $cnt $img
    [ -f "$gid-$cnt.jpg" ] || curl -s "http://${img/thumb/full}" -o "$gid-$cnt.jpg"
    cnt=$((cnt+1))
  done
}
imagefap.com/showfav() {
  gals=`curl -s "$1" | grep -o 'href="gallery.php[^&]*' | cut -d'=' -f 3`
  for gal in $gals; do
    imagefap.com/gallery "$gal"
  done
}
imagefap.com/profile() {
  gals=`curl -s -L "$1" | grep -o 'href="/gallery/[^"]*' | cut -d'"' -f 2`
  for gal in $gals; do
    imagefap.com/gallery "http://www.imagefap.com$gal"
  done
}
imagebam.com/image() {
  line=`curl -s "$1" | grep "<img id="`
  fname=`echo "$line" | cut -d'"' -f 2`
  url=`echo "$line" | grep -o 'http://[^"]*'`
  echo "$fname" "$url"
  curl -C - -s "$url" -o "$fname"
}
imagebam.com/gallery() {
  imgs=`curl -s "$1"|grep BB-Code|grep -o "URL=[^]]*"|cut -d'=' -f 2`
  for img in $imgs; do
    imagebam.com/image "$img"
  done
}

`get_site "$1"` "$1"
